package com.lemon.core.captcha.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lemon.core.captcha.constant.CaptchaConstant;
import com.lemon.core.captcha.domain.ImageCaptcha;
import com.lemon.core.captcha.service.ImageCaptchaService;
import com.wf.captcha.SpecCaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 图片验证码服务实现类
 *
 * @author pan
 * @since 2017-03-22
 */
@RequiredArgsConstructor
public class ImageCaptchaServiceImpl implements ImageCaptchaService {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public ImageCaptcha get() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String captchaCode = specCaptcha.text().toLowerCase();
        String captchaKey = IdUtil.simpleUUID();
        stringRedisTemplate.opsForValue().set(getCacheCaptchaKey(captchaKey), captchaCode, 60, TimeUnit.SECONDS);
        return new ImageCaptcha(captchaKey, specCaptcha.toBase64());
    }

    @Override
    public boolean verification(String captchaKey, String captchaCode) {
        // 从缓存取出正确的验证码和用户输入的验证码比对
        String correctValidateCode = stringRedisTemplate.opsForValue().get(getCacheCaptchaKey(captchaKey));
        boolean result = Objects.equals(captchaCode, correctValidateCode);
        if (result) {
            delete(captchaKey);
        }
        return result;
    }

    @Override
    public void delete(String captchaKey) {
        stringRedisTemplate.delete(getCacheCaptchaKey(captchaKey));
    }

    private String getCacheCaptchaKey(String captchaKey) {
        return CaptchaConstant.IMAGE_CAPTCHA_KEY_PREFIX + captchaKey;
    }
}
